package com.irun.ibuffet.utils;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.NameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.irun.ibuffet.R;
import com.irun.ibuffet.model.Response;

/***
 * @author huangsm
 * @date 2013-2-20
 * @email huangsanm@gmail.com
 * @desc 请求线程
 */
public class RequestTask extends AsyncTask<String, Integer, Object> {

	private Context mContext;
	// 方式
	private int mMethod;
	// 参数
	private List<NameValuePair> mParams;
	// 标识
	private boolean isSuc = false;

	private Class mClass;

	private Type mType;

	//回调
	private RequestListener mListener;
	
	//加载进度条
	private ProgressDialog mDialog;

	public RequestTask(List<NameValuePair> params, Class clas, int method,
			RequestListener callback) {
		this(null, params, clas, null, method, callback);
	}

	public RequestTask(Context context, List<NameValuePair> params, Class clas,
			int method, RequestListener callback) {
		this(context, params, clas, null, method, callback);
	}

	/**
	 * 返回list列表
	 * @param params
	 * @param type "Type type = new TypeToken<List<T>>() {}.getType()"
	 * @param method
	 * @param callback
	 */
	public RequestTask(List<NameValuePair> params, Type type, int method,
			RequestListener callback) {
		this(null, params, null, type, method, callback);
	}

	/**
	 * 有加载进度条，返回的list列表
	 * @param context
	 * @param params
	 * @param type "Type type = new TypeToken<List<T>>() {}.getType()"
	 * @param method
	 * @param callback
	 */
	public RequestTask(Context context, List<NameValuePair> params, Type type,
			int method, RequestListener callback) {
		this(context, params, null, type, method, callback);
	}

	public RequestTask(Context context, List<NameValuePair> params, Class clas,
			Type type, int method, RequestListener callback) {
		mContext = context;
		mClass = clas;
		mType = type;
		mMethod = method;
		mListener = callback;
		
		if(params != null && !params.isEmpty())
			mParams = new ArrayList<NameValuePair>(params);
	}

	@Override
	protected void onPreExecute() {
		if(mContext != null){
			final Resources res = mContext.getResources();
			mDialog = ProgressDialog.show(mContext, res.getString(R.string.progress_dialog_title), res.getString(R.string.progress_dialog_message), false);
		}
	}

	@Override
	protected Object doInBackground(String... params) {
		String url = params[0];
		if(TextUtils.isEmpty(url)){
			return Constants.REQUEST_ERROR_URL;
		}
		//开始请求
		Response resp = HttpUtils.getRequestEntity(url, mMethod, mParams);
		
		if(Constants.DEBUG){
			if(mParams != null && !mParams.isEmpty())
				System.out.println("params:" + Arrays.toString(mParams.toArray()));
			System.out.println(resp.toString());
		}
		
		//处理结果
		if(resp.getCode() != Constants.REQUEST_SUCCESS_CODE){
			return resp.getDesc();
		}
		
		String jsonData = resp.getResponse();
		System.out.println("jsonData:" + jsonData);
		//返回结果为空
		if(TextUtils.isEmpty(jsonData)){
			//数据库中没有记录jsonData为空
			if(resp.getCode() == Constants.REQUEST_SUCCESS_CODE){
				isSuc = true;
				return null;
			}
			return resp.getDesc();
		}
		
		String error = "";
		
		try {
			//解析数据
			JSONObject json = (JSONObject) new JSONTokener(jsonData).nextValue();
			int code = json.getInt("code");
			String response = json.getString("response");
			String desc = json.getString("desc");
			
			if(code != Constants.REQUEST_SUCCESS_CODE){
				return desc;
			}
			
			if(!TextUtils.isEmpty(response)){
				Object obj = response;
				if(mClass != null){
					obj = new Gson().fromJson(response, mClass);
				}
				
				if(mType != null){
					obj = new Gson().fromJson(response, mType);
				}
				isSuc = true;
				return obj;
			}
		} catch (JSONException e) {
			error = e.getMessage();
		}
		return error;
	}
	
	@Override
	protected void onPostExecute(Object result) {
		if(mDialog != null){
			mDialog.dismiss();
		}
		//设置回调
		if(mListener != null){
			mListener.callback(isSuc, result);
		}
	}
	
	
	/**
	 * 去除换行
	 * @param result
	 * @return
	 */
	public String replaceAll(String result){
		if(!TextUtils.isEmpty(result)){
			Pattern p = Pattern.compile("\\s*|\t|\r|\n");
			Matcher m = p.matcher(result);
			return m.replaceAll("");
		}
		return result;
	}
}
